import https from '../../utils/http';
import toastService from '../../utils/toast.service';
import dateHelper from '../../utils/date-helper';
import systemStatus from '../../utils/system-status';
import authService from '../../utils/auth';
import GlabalConfig from '../../utils/global-config';
var pageNo = 1,
  pageSize = 10,
  pageMallNo = 1,
  pageMallSize = 10,
  id, index, isEndList = false, isEndMallList = false;
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    shopOrderTabList: [{
      modeId: 0,
      modeType: "all",
      modeName: "全部"
    }, {
      modeId: 1,
      modeType: "notCompleted",
      modeName: "未完成"
    },
    {
      modeId: 2,
      modeType: "complete",
      modeName: "已完成"
    },
    {
      modeId: 3,
      modeType: "cancel",
      modeName: "已取消"
    },
    {
      modeId: 4,
      modeType: "afterSales",
      modeName: "退款/售后"
    }
    ],
    currentOrderTab: 0,
    list: [],
    tabType: "",
    keyWords: ""
  },
  clickScanTab: function(e){
    let _this = this;
    wx.scanCode({
      success(res) {
        console.log('扫码结果：', res.result);
        console.log('扫码类型：', res.scanType); // QR_CODE / EAN_13 等
        console.log('所扫内容：', res.charSet);
        
        // 自定义跳转地址
        const params = _this.parseQueryString(res.result);
        const action = params.action;
        if(action === "orderWriteOff"){
          const id = params.id;
          wx.navigateTo({
            url: `/pages/order/writeoff/writeoff?id=${id}`
          });
        }
      },
      fail(err) {
        console.log('扫码失败：', err);
      }
    });
  },
  searchInput: function(e){
      let keyWords = e.detail.value;
      new Promise((resolve, reject) => {
        //判断大标签页
        this.getOrderList(this.data.shopOrderTabList[this.data.currentOrderTab].modeType, keyWords);
        resolve([])
        this.setData({
          keyWords: keyWords
        })
      })
  },
   //点击切换 
   clickOrderTab: function (e) {
    console.log(e)
    console.log(e.currentTarget.dataset.current)
    if (this.data.currentOrderTab === e.currentTarget.dataset.current) {
      return false;
    } else {
      pageNo = 1;
      // 显示加载图标
      this.setData({
        currentOrderTab: e.currentTarget.dataset.current
      });
      //console.log(this.data.pointsOrderTabList[e.target.dataset.current].modeType);
      // if (this.data.currentTab == 0) {
      //   this.setData({
      //     modeType:this.data.shopOrderTabList[e.target.dataset.current].modeType
      //   })
      //   this.getOrderList(this.data.shopOrderTabList[e.target.dataset.current].modeType, this.data.keyWords);
      // }
      // if (this.data.currentTab == 1) {
      //   this.setData({
      //     modeType:this.data.pointsOrderTabList[e.target.dataset.current].modeType
      //   })
      //   this.getMallOrderList(this.data.pointsOrderTabList[e.target.dataset.current].modeType, this.data.keyWords);
      // }
    }
  },
  // 滑动切换tab
  bindSlideChange: function (e) {
    console.log(e)
    // if (e.detail.current == 1) {
    //   if (this.data.mallList.length <= 0) {
    //     this.getMallOrderList();
    //   }
    // }
    pageNo = 1;
    this.setData({
      currentOrderTab: e.detail.current
    });
    this.setData({
      modeType:this.data.shopOrderTabList[e.detail.current].modeType
    })
    this.getOrderList(this.data.shopOrderTabList[e.detail.current].modeType, this.data.keyWords);
  },
  getOrderList(tabType, keyWords) {
    toastService.showLoading("正在加载...");
    https.request('/api-order/rest/merchant/order/list', {
      pageNo: pageNo,
      pageSize: pageSize,
      tabType: tabType,
      keyWords: keyWords
    }).then(result => {
      toastService.hideLoading();
      if (result.success) {
        result.data.records.forEach(res => {
          res.createTime = dateHelper.fmtDate(res.createTime);
          res.statusText = systemStatus.statusText(res.status);
          res.paymentModeText = systemStatus.paymentModeText(res.paymentMode);
          res.shopLogoImg= GlabalConfig.ossUrl+res.shopLogoImg;
        })
        this.setData({
          list: result.data.records
        })
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    pageNo = 1;
      pageSize = 10;
      isEndList = false;
      this.getOrderList(this.data.shopOrderTabList[this.data.currentOrderTab].modeType,this.data.keyWords);
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },
    /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    toastService.showLoading("正在加载...");
    

      if (isEndList) {
        toastService.showToast("没有更多啦~");
        return;
      }
      pageNo = pageNo + 1;
      pageSize = 10;
      https.request('/api-order/rest/merchant/order/list', {
        pageNo: pageNo,
        pageSize: pageSize,
        tabType: this.data.shopOrderTabList[this.data.currentOrderTab].modeType,
        keyWords: this.data.keyWords
      }).then(result => {
        toastService.hideLoading();
        if (result.success) {
          if (result.data.records.length > 0) {
            result.data.records.forEach(res => {
              res.createTime = dateHelper.formatDate(res.createTime);
              res.statusText = systemStatus.statusText(res.status);
              res.shopLogoImg= GlabalConfig.ossUrl+res.shopLogoImg;
              this.data.list.push(
                res
              )
            })
            this.setData({
              list: this.data.list
            })
            return;
          }
          isEndList = true;
          toastService.showToast("没有更多啦~");
          pageNo = pageNo - 1;
        }
      })

  },
  getHeight() {
    //获取用户手机系统信息
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        let winHeight = res.windowHeight; //获取高度
        //获取class为settlement-view并减去这个高度，自适应scrollview的高度
        const query = wx.createSelectorQuery()
        query.select('.swiper-content').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function (res) {
          console.log(winHeight - res[0].height)
          that.setData({
            winHeight: winHeight - res[0].height
          });
        })
      }
    });
  },
  orderDetailsTap(e) {
    id = e.currentTarget.dataset.id;
    index = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: './detail/detail?id=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    pageNo = 1;
    this.getHeight();
    // this.getMallOrderList("", "");
    // this.setData({
    //   search: this.search.bind(this),
    //   currentTab:options.currentTab,
    //   currentOrderTab:options.currentOrderTab,
    //   modeType:options.modeType
    // })
    // this.selectTabNumber();
    // this.selectMallTabNumber();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrderList(this.data.shopOrderTabList[this.data.currentOrderTab].modeType, this.data.keyWords);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  parseQueryString(url) {
    const queryString = url.split('?')[1] || '';
    const params = {};
    queryString.split('&').forEach(pair => {
      const [key, value] = pair.split('=');
      if (key) params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    });
    return params;
  }
})